<template>
  <div class="login-container">
    <!-- Three.js 波浪网面 -->
    <div ref="waveContainer" class="wave-container"></div>
    
    <div class="login-box">
      <div class="login-header">
        <h1>🌱 绿色OTA管理系统</h1>
        <p>智能低碳 · 绿色升级 · 可持续发展</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            🔐 绿色登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>🌍 默认账户：admin / admin123 | 为地球减碳贡献力量</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { authService, type LoginRequest } from '@/services/authService'
import * as THREE from 'three'

const router = useRouter()
const loading = ref(false)
const waveContainer = ref<HTMLElement>()

// Three.js 相关变量
let scene: THREE.Scene
let camera: THREE.PerspectiveCamera
let renderer: THREE.WebGLRenderer
let geometry: THREE.PlaneGeometry
let material: THREE.PointsMaterial
let points: THREE.Points
let animationId: number

// 表单数据
const loginForm = reactive<LoginRequest>({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const loginFormRef = ref()

// 初始化 Three.js 波浪动画
const initWaveAnimation = () => {
  if (!waveContainer.value) return

  // 创建场景
  scene = new THREE.Scene()
  
  // 创建相机
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.set(0, 80, 120)
  camera.lookAt(0, 0, 0)
  
  // 创建渲染器
  renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  renderer.setClearColor(0x000000, 0) // 透明背景
  waveContainer.value.appendChild(renderer.domElement)
  
  // 创建波浪网格几何体 - 铺满屏幕
  const aspectRatio = window.innerWidth / window.innerHeight
  const width = 300 * aspectRatio // 根据屏幕比例调整宽度
  const height = 300
  const widthSegments = Math.floor(80 * aspectRatio) // 根据比例调整网格密度
  const heightSegments = 80
  
  geometry = new THREE.PlaneGeometry(width, height, widthSegments, heightSegments)
  
  // 创建点材质 - 圆点效果
  material = new THREE.PointsMaterial({
    color: 0x4caf50,
    size: 2.0,
    transparent: true,
    opacity: 0.7,
    sizeAttenuation: true, // 根据距离调整大小
    alphaTest: 0.1,
    vertexColors: false
  })
  
  // 创建圆点纹理
  const canvas = document.createElement('canvas')
  canvas.width = 32
  canvas.height = 32
  const context = canvas.getContext('2d')!
  
  // 绘制圆形
  context.clearRect(0, 0, 32, 32)
  context.fillStyle = '#ffffff'
  context.beginPath()
  context.arc(16, 16, 15, 0, Math.PI * 2)
  context.fill()
  
  const texture = new THREE.CanvasTexture(canvas)
  material.map = texture
  
  // 创建点云
  points = new THREE.Points(geometry, material)
  points.rotation.x = -Math.PI / 2.2 // 稍微倾斜一点
  points.position.y = -40
  scene.add(points)
  
  // 添加环境光
  const ambientLight = new THREE.AmbientLight(0x4caf50, 0.3)
  scene.add(ambientLight)
  
  // 添加点光源
  const pointLight = new THREE.PointLight(0x8bc34a, 1.2, 500)
  pointLight.position.set(0, 100, 80)
  scene.add(pointLight)
  
  // 添加第二个光源增强效果
  const pointLight2 = new THREE.PointLight(0x66bb6a, 0.8, 400)
  pointLight2.position.set(-100, 60, 100)
  scene.add(pointLight2)
  
  // 开始动画循环
  animate()
}

// 动画循环函数
const animate = () => {
  animationId = requestAnimationFrame(animate)
  
  // 更新波浪
  updateWave()
  
  // 渲染场景
  renderer.render(scene, camera)
}

// 更新波浪动画
const updateWave = () => {
  const time = Date.now() * 0.0008 // 稍微放慢速度
  const positions = geometry.attributes.position.array as Float32Array
  
  for (let i = 0; i < positions.length; i += 3) {
    const x = positions[i]
    const y = positions[i + 1]
    
    // 创建更自然的波浪效果
    const wave1 = Math.sin((x * 0.08) + (time * 2)) * 12
    const wave2 = Math.sin((y * 0.06) + (time * 1.5)) * 8
    const wave3 = Math.sin((x * 0.03) + (y * 0.04) + (time * 1.2)) * 15
    const wave4 = Math.cos((x * 0.02) + (y * 0.03) + (time * 0.8)) * 6
    
    positions[i + 2] = wave1 + wave2 + wave3 + wave4
  }
  
  geometry.attributes.position.needsUpdate = true
}

// 处理窗口大小变化
const handleResize = () => {
  if (camera && renderer) {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    
    // 重新调整网格大小以适应新的屏幕比例
    if (geometry && points) {
      scene.remove(points)
      geometry.dispose()
      
      const aspectRatio = window.innerWidth / window.innerHeight
      const width = 300 * aspectRatio
      const height = 300
      const widthSegments = Math.floor(80 * aspectRatio)
      const heightSegments = 80
      
      geometry = new THREE.PlaneGeometry(width, height, widthSegments, heightSegments)
      points = new THREE.Points(geometry, material)
      points.rotation.x = -Math.PI / 2.2
      points.position.y = -40
      scene.add(points)
    }
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    await authService.login(loginForm)
    ElMessage.success('登录成功')
    
    // 跳转到首页或者回到之前的页面
    const redirect = router.currentRoute.value.query.redirect as string
    router.push(redirect || '/')
    
  } catch (error: any) {
    if (error.response?.status === 401) {
      ElMessage.error('用户名或密码错误')
    } else {
      ElMessage.error('登录失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时的处理
onMounted(() => {
  if (authService.isAuthenticated()) {
    router.push('/')
  } else {
    // 延迟初始化，确保DOM已渲染
    setTimeout(() => {
      initWaveAnimation()
    }, 100)
    
    window.addEventListener('resize', handleResize)
  }
})

// 组件卸载时清理
onBeforeUnmount(() => {
  if (animationId) {
    cancelAnimationFrame(animationId)
  }
  
  if (renderer && waveContainer.value) {
    waveContainer.value.removeChild(renderer.domElement)
    renderer.dispose()
  }
  
  if (geometry) geometry.dispose()
  if (material) material.dispose()
  
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 25%, #00c9ff 50%, #92fe9d 75%, #00c9ff 100%);
  overflow: hidden;
}

/* Three.js 波浪网面容器 */
.wave-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.wave-container canvas {
  display: block;
  width: 100%;
  height: 100%;
}

.login-box {
  position: relative;
  z-index: 10;
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.92);
  border-radius: 16px;
  box-shadow: 
    0 12px 40px rgba(76, 175, 80, 0.15),
    0 4px 16px rgba(139, 195, 74, 0.1);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(139, 195, 74, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  color: #2e7d32;
  margin-bottom: 8px;
  font-size: 28px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(76, 175, 80, 0.1);
}

.login-header p {
  color: #4caf50;
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  background: linear-gradient(135deg, #4caf50 0%, #8bc34a 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: linear-gradient(135deg, #43a047 0%, #7cb342 100%);
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(76, 175, 80, 0.3);
}

.login-footer {
  text-align: center;
  color: #689f38;
  font-size: 12px;
}

.login-footer p {
  margin: 0;
}

/* 输入框样式调整 */
.login-form :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(139, 195, 74, 0.3);
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper:hover) {
  border-color: rgba(76, 175, 80, 0.5);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  border-color: #4caf50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}
</style> 